package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.TicketBusiness;
import com.ruoyi.system.enums.BusType;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.TicketCommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TicketCustomerMapper;
import com.ruoyi.system.domain.TicketCustomer;
import com.ruoyi.system.service.ITicketCustomerService;

import javax.validation.Validator;

/**
 * 客户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-15
 */
@Service
public class TicketCustomerServiceImpl implements ITicketCustomerService
{
    private static final Logger log = LoggerFactory.getLogger(TicketCustomerServiceImpl.class);

    @Autowired
    private TicketCustomerMapper ticketCustomerMapper;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private TicketCommonService commonService;

    @Autowired
    protected Validator validator;

    /**
     * 查询客户信息
     *
     * @param customerNo 客户信息主键
     * @return 客户信息
     */
    @Override
    public TicketCustomer selectTicketCustomerByCustomerNo(String customerNo)
    {
        return ticketCustomerMapper.selectTicketCustomerByCustomerNo(customerNo);
    }

    @Override
    public String importCustomer(List<TicketCustomer> customerList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(customerList) || customerList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TicketCustomer customer : customerList)
        {
            try
            {
                // 验证是否存在这个用户
                TicketCustomer u = ticketCustomerMapper.selectTicketCustomerByPhone(customer.getCustomerPhone());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, customer);
                    customer.setCreateBy(operName);
                    this.insertTicketCustomer(customer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + customer.getCustomerName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, customer);
                    customer.setUpdateBy(operName);
                    this.updateTicketCustomer(customer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + customer.getCustomerName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户 " + customer.getCustomerName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + customer.getCustomerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public TicketCustomer selectTicketCustomerByCustomerName(String customerName) {
        return ticketCustomerMapper.selectTicketCustomerByCustomerName(customerName);
    }

    /**
     * 查询客户信息列表
     *
     * @param ticketCustomer 客户信息
     * @return 客户信息
     */
    @Override
    public List<TicketCustomer> selectTicketCustomerList(TicketCustomer ticketCustomer)
    {
//        return ticketCustomerMapper.selectTicketCustomerList(ticketCustomer);
        List<TicketCustomer> allCustomerByCurrentUser = commonService.getAllCustomerByCurrentUser();
        List<String> allBusinessByCurrentUserNos = allCustomerByCurrentUser.stream().map(TicketCustomer::getCustomerNo).collect(Collectors.toList());
        List<TicketCustomer> ticketCustomers = ticketCustomerMapper.selectTicketCustomerList(ticketCustomer);
        List<String> ticketCustomersNos = ticketCustomers.stream().map(TicketCustomer::getCustomerNo).collect(Collectors.toList());
        ticketCustomersNos.retainAll(allBusinessByCurrentUserNos);
        return allCustomerByCurrentUser.stream().filter(p->ticketCustomersNos.contains(p.getCustomerNo())).collect(Collectors.toList());
    }

    /**
     * 新增客户信息
     *
     * @param ticketCustomer 客户信息
     * @return 结果
     */
    @Override
    public int insertTicketCustomer(TicketCustomer ticketCustomer)
    {
        if(StringUtils.isEmpty(ticketCustomer.getCustomerNo())){
            ticketCustomer.setCustomerNo(UUID.randomUUID().toString());
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ticketCustomer.setCreateBy(loginUser.getUsername());
        ticketCustomer.setCreateTime(DateUtils.getNowDate());
        //同步新增客户用户
        insertSysUser(ticketCustomer);
        return ticketCustomerMapper.insertTicketCustomer(ticketCustomer);
    }

    /**
     * 同步新增客户对应的用户
     * @param ticketCustomer
     * @return
     */
    public int insertSysUser(TicketCustomer ticketCustomer){
        SysUser customerUser = new SysUser();
        String customerPhone = ticketCustomer.getCustomerPhone();
        String customerNo = ticketCustomer.getCustomerNo();
        //用户登录账户默认为手机号码
        customerUser.setUserName(customerPhone);
        customerUser.setNickName(ticketCustomer.getCustomerName());
        customerUser.setPhonenumber(customerPhone);
        customerUser.setSex("0");
        customerUser.setRoleId(102L);
        Long[] roleIds = new Long[1];
        roleIds[0] = 102L;
        customerUser.setRoleIds(roleIds);
        //客户自动设置为当前登录人(默认客户经理)所在部门
        LoginUser loginUser = SecurityUtils.getLoginUser();
        customerUser.setDeptId(loginUser.getDeptId());
        //客户用户备注为唯一编号，便于联动删除与唯一标识
        customerUser.setRemark(customerNo);
        //客户用户登录密码默认为手机号码后6位
        customerUser.setPassword(SecurityUtils.encryptPassword(customerPhone.substring(customerPhone.length()-6)));
        return userService.insertUser(customerUser);
    }
    /**
     * 修改客户信息
     *
     * @param ticketCustomer 客户信息
     * @return 结果
     */
    @Override
    public int updateTicketCustomer(TicketCustomer ticketCustomer)
    {
        ticketCustomer.setUpdateTime(DateUtils.getNowDate());
        return ticketCustomerMapper.updateTicketCustomer(ticketCustomer);
    }

    /**
     * 批量删除客户信息
     *
     * @param customerNos 需要删除的客户信息主键
     * @return 结果
     */
    @Override
    public int deleteTicketCustomerByCustomerNos(String[] customerNos)
    {
        return ticketCustomerMapper.deleteTicketCustomerByCustomerNos(customerNos);
    }

    /**
     * 删除客户信息信息
     *
     * @param customerNo 客户信息主键
     * @return 结果
     */
    @Override
    public int deleteTicketCustomerByCustomerNo(String customerNo)
    {
        //同步禁用客户用户账号
        SysUser sysUser = userService.selectByRemark(customerNo);
        userService.deleteUserById(sysUser.getUserId());
        return ticketCustomerMapper.deleteTicketCustomerByCustomerNo(customerNo);
    }
}
